package com.mxpio.webapp.socket;

import cn.hutool.extra.servlet.ServletUtil;
import com.mxpio.webapp.entity.MonitorSsh;
import com.mxpio.webapp.service.IMonitorSshService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * socket 拦截器
 *
 * @author: Cheng
 * @date: 2022/11/12
 */
@Configuration
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Autowired
    private IMonitorSshService sshService;

    /**
     * Handler处理前调用
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest();
            //ssh信息
            String id = httpServletRequest.getParameter("id");
            if (StringUtils.isEmpty(id)) {
                return false;
            }
            MonitorSsh monitorSsh = sshService.selectById(id);
            if (monitorSsh == null) {
                return false;
            }
            attributes.put("monitorSsh", monitorSsh);

            //获取客户端ip
            String ip = ServletUtil.getClientIP(httpServletRequest);
            attributes.put("ip", ip);
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
